package com.ytc.media.service.impl;


import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;

import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ytc.commons.constants.CommonConstants;
import com.ytc.commons.constants.CourseConstants;
import com.ytc.commons.model.dto.*;
import com.ytc.commons.model.vo.*;
import com.ytc.commons.utils.BeanHelper;
import com.ytc.media.config.VodTemplate;
import com.ytc.media.domain.Media;
import com.ytc.media.mappers.MediaMapper;
import com.ytc.media.service.MediaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ytc.web.interceptor.AuthInfoHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author jiuye145
 * @since 2023-04-04
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    private VodTemplate vodTemplate;

    @Override//获取上传凭证
    public ResponseResult<VodUploadVo> creatToken(VodUploadDto dto) throws Exception {
        //请求阿里云
        CreateUploadVideoResponse response = vodTemplate.createUploadVideo(dto.getTitle(), dto.getFileName());
        //构造返回
        VodUploadVo vo =new VodUploadVo();
        vo.setRequestId(response.getRequestId());
        vo.setUploadAddress(response.getUploadAddress());
        vo.setUploadAuth(response.getUploadAuth());
        vo.setVideoId(response.getVideoId());
        vo.setUserId(AuthInfoHolder.getUserId().toString());
        return ResponseResult.okResult(vo);
    }


    //刷新上传凭证
    @Override
    public ResponseResult<VodUploadVo> refreshToken(String videoId) throws Exception {
        //请求阿里云
        RefreshUploadVideoResponse response = vodTemplate.refreshUploadVideo(videoId);
        //构造返回
        VodUploadVo vo =new VodUploadVo();
        vo.setRequestId(response.getRequestId());
        vo.setUploadAddress(response.getUploadAddress());
        vo.setUploadAuth(response.getUploadAuth());
        vo.setVideoId(response.getVideoId());
        vo.setUserId(AuthInfoHolder.getUserId().toString());
        return ResponseResult.okResult(vo);
    }

    //保存视频
    @Override
    public ResponseResult saveMedia(MediaDto dto) throws Exception{
        //1.根据dto创建Media对象
        Media media = BeanHelper.copyProperties(dto,Media.class);

           //设置阿里云的视频时长
        GetPlayInfoResponse playInfo = vodTemplate.getPlayInfo(dto.getFileId());
        List<GetPlayInfoResponse.PlayInfo> list = playInfo.getPlayInfoList();
        GetPlayInfoResponse.PlayInfo info = list.get(0);
        //获取播放地址
        String playURL = info.getPlayURL();
        //获取播放时间长度
        String duration = info.getDuration();

        media.setUrl(playURL);
        media.setTimelength(duration);

        //设置其他参数
            media.setCompanyName(AuthInfoHolder.getAuthInfo().getCompanyName());
            media.setCreateDate(new Date());
            media.setStatus(CommonConstants.USING_FLAG.toString());
            media.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS);
        //2.保存
        this.save(media);
        //3.
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<MediaVo> findAll(PageRequest request, MediaQueryDto dto) {
        Page<Media> pageParam = new Page<>(request.getPageNo(),request.getPageSize());

        //查询条件
        LambdaQueryWrapper<Media> qw = new LambdaQueryWrapper<>();

        if(!StringUtils.isEmpty(dto.getType())) {
            qw.eq(Media::getType,dto.getType());
        }
        if(!StringUtils.isEmpty(dto.getFilename())) {
            qw.like(Media::getFilename,dto.getFilename());
        }

        qw.eq(Media::getStatus,"1");
        if(!StringUtils.isEmpty(dto.getAuditStatus())) {
            qw.eq(Media::getAuditStatus,dto.getAuditStatus());
        }

        Page<Media> page = this.page(pageParam,qw);
         List<Media> list = page.getRecords();
         List<MediaVo> voList = BeanHelper.copyWithCollection(list,MediaVo.class);
        return new PageResponseResult(page.getTotal(),voList);
    }

    //视频预览操作
    @Override
    public ResponseResult<String> previewMedia(Long mediaId) throws Exception{

        Media media = this.getById(mediaId);

        //由于阿里云存在视频过期的可能需要实时去仓库查看是否更新了
        GetPlayInfoResponse playInfo = vodTemplate.getPlayInfo(media.getFileId());
        List<GetPlayInfoResponse.PlayInfo> list = playInfo.getPlayInfoList();
        GetPlayInfoResponse.PlayInfo info = list.get(0);
        //获取播放地址
        String playURL = info.getPlayURL();
        //判断数据库的播放地址和阿里云的是否一致
        String playUrl = media.getUrl();
        if(!playURL.equals(playUrl)){
            //不一致更新数据库的url
            media.setUrl(playURL);
            this.updateById(media);
            return ResponseResult.okResult(playURL);
        }else {
            return ResponseResult.okResult(playUrl);
        }
    }

    // //视频移除操作
    @Override
    public ResponseResult<Boolean> deleteMedia(Long mediaId) {
        LambdaUpdateWrapper<Media> qw = new LambdaUpdateWrapper<>();
        qw.set(Media::getStatus,CommonConstants.DELETE_FLAG);
        qw.eq(Media::getId,mediaId);
        this.update(qw);
        return ResponseResult.okResult(true);
    }

    //根据id查询视频
    @Override
    public ResponseResult<MediaVo> findById(Long mediaId) {
        Media media = this.getById(mediaId);
        MediaVo mediaVo = BeanHelper.copyProperties(media, MediaVo.class);
        return ResponseResult.okResult(mediaVo);
    }

    //管理员审核视频
    @Override
    public ResponseResult auditMedia(MediaAuditDto dto) {
        LambdaUpdateWrapper<Media> qw = new LambdaUpdateWrapper<>();
        qw.set(Media::getAuditMind,dto.getAuditMind());
        qw.set(Media::getAuditStatus,dto.getAuditStatus());
        qw.eq(Media::getId,dto.getId());
        this.update(qw);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<ResourceVo> findMediaUrl(Long mediaId) throws Exception{
        //media id获取fileid

        //从阿里云获取
        //获取播放地址
        Media byId = this.getById(mediaId);
        //获取阿里云视频id
        String fileId = byId.getFileId();
        GetPlayInfoResponse playInfo = vodTemplate.getPlayInfo(fileId);
        //获取视频播放地址
        GetPlayInfoResponse.PlayInfo playInfo1 = playInfo.getPlayInfoList().get(0);
        String playURL = playInfo1.getPlayURL();
        //返回
        ResourceVo resourceVo = new ResourceVo();
        resourceVo.setPlayUrl(playURL);
        return ResponseResult.okResult(resourceVo);

    }
}
